<template>
  <div class="home">
    <el-header class="fixed-header">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
        background-color="#000000"
        text-color="#fff"
        active-text-color="#FFBD00"
      >
        <el-menu-item class="logo-item">
          <div class="navbar-header">
            <a
              href="/"
              data-axc="navigation"
              data-axa="click"
              data-axl="logo"
              class="navbar-brand"
              ><img
                src="https://ideascdn.lego.com/public/_shared/lego/img/headlogo@2x.png"
                alt="LEGO IDEAS Logo"
                nopin="open"
                class="community-logo"
            /></a>
          </div>
        </el-menu-item>

        <!-- 移动端汉堡菜单按钮 -->
        <div class="mobile-menu-button" @click="toggleMobileMenu">
          <i class="el-icon-menu"></i>
        </div>

        <!-- 桌面端导航 -->
        <div class="menu-items-container desktop-only">
          <el-menu-item class="el-menu-item" index="1">首页</el-menu-item>
          <el-menu-item class="el-menu-item" index="2">社区</el-menu-item>
          <el-menu-item class="el-menu-item" index="3">任务</el-menu-item>
          <el-menu-item v-if="isAdmin" class="el-menu-item" index="4"
            >后台</el-menu-item
          >
        </div>
        
        <div class="search-container desktop-only">
          <el-input
            v-model="searchQuery"
            placeholder="搜索..."
            prefix-icon="el-icon-search"
            class="header-search"
          >
            <el-select
              v-model="searchType"
              slot="append"
              placeholder="类型"
              style="width: 130px"
            >
              <el-option label="全部" value="all" />
              <el-option label="社区" value="idea" />
              <el-option label="任务" value="job" />
            </el-select>
          </el-input>
        </div>
        
        <!-- 添加通知图标 -->
        <div class="notification-container desktop-only">
          <notification-center />
        </div>
        
        <el-submenu class="avatar-item desktop-only" index="user">
          <template v-slot:title>
            <span class="avatar-with-text" :class="{ 'admin-avatar': isAdmin }">
              <div class="avatar">
                <img
                  :src="userAvatar"
                  :alt="username"
                  class="avatar-img"
                  @error="handleAvatarError"
                />
                <span v-if="isAdmin" class="admin-badge">
                  <i class="el-icon-star-on"></i>
                </span>
                <span v-if="unreadCount > 0" class="unread-notification-badge"></span>
              </div>
              <label class="avatar-label">{{ username }}</label>
            </span>
          </template>
          <el-menu-item index="9" :class="{ 'admin-menu-item': isAdmin }">
            通知
            <span v-if="unreadCount > 0" class="menu-notification-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
          </el-menu-item>
          <el-menu-item index="6" :class="{ 'admin-menu-item': isAdmin }">作品</el-menu-item>
          <el-menu-item index="7" :class="{ 'admin-menu-item': isAdmin }">设置</el-menu-item>
          <el-menu-item index="8" :class="{ 'admin-menu-item': isAdmin }">登出</el-menu-item>
        </el-submenu>
      </el-menu>

      <!-- 移动端侧边导航菜单 -->
      <div class="mobile-menu" :class="{ 'mobile-menu-active': mobileMenuOpen }">
        <div class="mobile-menu-header">
          <div class="mobile-user-info">
            <div class="avatar">
              <img
                :src="userAvatar"
                :alt="username"
                class="avatar-img"
                @error="handleAvatarError"
              />
              <span v-if="unreadCount > 0" class="unread-notification-badge"></span>
            </div>
            <span class="mobile-username">{{ username }}</span>
          </div>
          <div class="mobile-menu-close" @click="toggleMobileMenu">
            <i class="el-icon-close"></i>
          </div>
        </div>
        
        <div class="mobile-search">
          <el-input
            v-model="searchQuery"
            placeholder="搜索..."
            prefix-icon="el-icon-search"
            class="mobile-header-search"
          >
            <el-select
              v-model="searchType"
              slot="append"
              placeholder="类型"
              style="width: 90px"
            >
              <el-option label="全部" value="all" />
              <el-option label="社区" value="idea" />
              <el-option label="任务" value="job" />
            </el-select>
          </el-input>
        </div>
        
        <div class="mobile-menu-items">
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('1')">首页</div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('2')">社区</div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('3')">任务</div>
          <div v-if="isAdmin" class="mobile-menu-item" @click="handleMobileMenuSelect('4')">后台</div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('9')">
            通知
            <span v-if="unreadCount > 0" class="mobile-menu-notification-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
          </div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('6')">作品</div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('7')">设置</div>
          <div class="mobile-menu-item" @click="handleMobileMenuSelect('8')">登出</div>
        </div>
      </div>
      
      <!-- 移动菜单打开时的遮罩层 -->
      <div 
        v-if="mobileMenuOpen" 
        class="mobile-menu-overlay"
        @click="toggleMobileMenu"
      ></div>
    </el-header>
    <el-main class="el-main">
      <router-view></router-view>
    </el-main>
    
    <!-- 添加移动端底部导航栏 -->
    <MobileNav />
  </div>
</template>

<script>
import defaultAvatar from "@/assets/images/default-avatar.jpg";
import apiClient from '@/api/api';
import MobileNav from '@/components/MobileNav.vue';
import { getRole, getUsername } from "@/api/auth";
import NotificationCenter from '@/components/NotificationCenter.vue';
import { getUnreadNotificationsCount, markAllNotificationsAsRead } from '@/api/api';

export default {
  components: {
    MobileNav,
    NotificationCenter
  },
  data() {
    return {
      activeIndex: "1", // 默认激活索引
      username: getUsername() || "Guest", // 初始值
      searchQuery: "",
      searchType: "all",
      avatarUrl: "",
      mobileMenuOpen: false, // 移动菜单状态
      unreadCount: 0, // 添加未读通知计数
    };
  },
  computed: {
    isAdmin() {
      return getRole() === "admin";
    },
    userAvatar() {
      return this.avatarUrl || defaultAvatar;
    },
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await apiClient.get('/user/info')
        const userInfo = response.data
        this.username = userInfo.username
        // 检查并处理头像URL的协议
        let profileUrl = userInfo.profilePictureUrl
        if (profileUrl && profileUrl.startsWith('https://')) {
          profileUrl = 'http://' + profileUrl.substring(8)
        }
        this.avatarUrl = profileUrl
        console.log('用户信息:', userInfo)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.username = getUsername() || 'Guest'
        this.avatarUrl = ''
      }
    },

    // 获取未读通知数量
    async fetchUnreadCount() {
      try {
        const response = await getUnreadNotificationsCount();
        console.log('获取未读通知数量响应:', response);
        // 检查不同的返回格式
        if (response.hasOwnProperty('count')) {
          this.unreadCount = response.count || 0;
        } else if (typeof response === 'number') {
          this.unreadCount = response;
        } else {
          this.unreadCount = 0;
        }
      } catch (error) {
        console.error('获取未读通知数量失败:', error);
        this.unreadCount = 0;
      }
    },

    /**
     * 处理菜单项的选择。
     * @param {string} index - 选中的菜单项索引。
     */
    handleSelect(index) {
      const routes = {
        1: "Home",
        2: "Idea",
        3: "job",
        4: "admin_job_list",
        7: "user_set",
        8: "login",
        9: "notifications"
      };

      const targetRoute = { name: routes[index] || "Home" };

      // 如果是登出操作，清除 token
      if (index === "8") {
        localStorage.removeItem("token");
      }
      
      // 如果点击的是通知菜单项，标记所有通知为已读
      if (index === "9" && this.unreadCount > 0) {
        this.markAllAsRead();
      }

      // 检查是否已经在目标路由
      if (this.$route.name === targetRoute.name) {
        console.log("Already at the target route:", targetRoute.name);
        return; // 避免重复导航
      }

      // 跳转到对应的路由
      this.$router.push(targetRoute);

      // 更新 activeIndex
      this.activeIndex = index;
    },

    // 添加标记所有通知为已读的方法
    async markAllAsRead() {
      try {
        await markAllNotificationsAsRead();
        // 更新未读通知计数
        this.unreadCount = 0;
        console.log('已全部标记为已读');
      } catch (error) {
        console.error('标记已读失败:', error);
      }
    },

    // 处理移动菜单选择
    handleMobileMenuSelect(index) {
      // 如果点击的是通知菜单项，标记所有通知为已读
      if (index === "9" && this.unreadCount > 0) {
        this.markAllAsRead();
      }
      
      this.toggleMobileMenu(); // 点击后关闭菜单
      this.handleSelect(index);
    },

    // 切换移动菜单显示状态
    toggleMobileMenu() {
      this.mobileMenuOpen = !this.mobileMenuOpen;
      // 禁止/恢复body滚动
      if (this.mobileMenuOpen) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
    },

    handleAvatarError(e) {
      e.target.src = defaultAvatar;
    },
  },
  watch: {
    /**
     * 监听路由变化并相应地更新 activeIndex。
     * @param {Object} to - 目标路由对象。
     */
    $route(to) {
      const routeMapping = {
        Home: "1",
        Idea: "2",
        job: "3",
        admin_job_list: "4",
        activity_detail: "5",
        post_detail: "5",
        challenge_detail: "5",
        notifications: "notifications"
      };
      this.activeIndex = routeMapping[to.name] || "1"; // 如果没有匹配，默认 "1"
    },
  },
  async mounted() {
    // 获取用户信息
    await this.fetchUserInfo()

    // 获取未读通知数量
    await this.fetchUnreadCount()

    // 定时轮询获取未读通知数量
    this.notificationInterval = setInterval(() => {
      this.fetchUnreadCount();
    }, 30000); // 每30秒轮询一次

    // 监听 localStorage 变化，重新获取用户信息
    window.addEventListener("storage", this.fetchUserInfo);
  },
  beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener("storage", this.fetchUserInfo);
    
    // 清除轮询定时器
    if (this.notificationInterval) {
      clearInterval(this.notificationInterval);
    }
  },
};
</script>

<style scoped>
.home {
  width: 100%;
}

/* 菜单项的样式，使它们上下居中 */
.el-menu-item {
  display: flex;
  align-items: center;
  font-family: "Microsoft YaHei", sans-serif;
  font-size: 46px;
  color: #fff;
  padding: 0 16px;
  line-height: 24px;
  margin: 0 30px;
}

/* 固定顶部样式 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #000000;
  z-index: 1000;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

/* 为内容添加顶部内边距，避免被固定头部遮挡 */
.el-main {
  margin-top: 60px;
  padding-top: 20px;
}

/* 头像 项样式 */
.avatar-item {
  position: absolute;
  right: 20px;
}

.avatar-with-text {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 控制图片和文字之间的间距 */
  padding: 0 10px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%; /* 确保容器是圆形 */
  overflow: hidden;
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  position: relative; /* 添加相对定位，用于放置红点指示器 */
}

.avatar-img {
  width: 100%; /* 确保图片宽度填充容器 */
  height: 100%; /* 确保图片高度填充容器 */
  object-fit: cover; /* 保持图片比例，同时填充容器 */
}

body {
  background-color: #f2f4f7;
  margin: 0;
  padding: 0;
  font-family: "Cera-Bold", sans-serif;
}

.el-menu-demo {
  display: flex;
  align-items: center;
  height: 60px;
  border: none;
  padding: 0 20px;
  position: relative;
}

/* LOGO 项样式 */
.logo-item {
  position: absolute;
  left: 20px;
  height: 60px;
  display: flex;
  align-items: center;
}

.el-menu-demo .el-menu-item {
  font-family: "Microsoft YaHei", sans-serif;
  font-size: 16px;
  color: rgb(255, 255, 255);
  padding: 8px 16px;
  line-height: 24px;
  text-align: left;
}

.custom-carousel-item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

/* 导航栏头部样式 */
.navbar-header {
  text-align: left;
  font-family: "Cera Pro", sans-serif;
  font-size: 16px;
  font-weight: 300;
  line-height: 1.5rem;
  color: #fff;
}

/* 导航栏品牌链接样式 */
.navbar-header .navbar-brand {
  display: inline-block;
  text-decoration: none;
}

/* 社区Logo样式 */
.navbar-header .navbar-brand .community-logo {
  height: 40px; /* 固定高度 */
  display: block;
}

/* 导航菜单项容器 */
.menu-items-container {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 搜索框容器样式 */
.search-container {
  position: absolute;
  right: 180px;
  width: 300px;
}

/* 通知图标容器 */
.notification-container {
  position: absolute;
  right: 100px;
  display: flex;
  align-items: center;
  height: 60px;
}

/* 搜索框样式 */
.header-search {
  width: 100%;
  margin-right: 40px;
}

.header-search :deep(.el-input__inner) {
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  height: 36px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-right: none;
  color: #fff;
}

.header-search :deep(.el-input__icon) {
  color: #fff;
}

/* 选择框样式 */
.header-search :deep(.el-input-group__append) {
  background-color: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-left: none;
  padding: 0;
  position: relative;
}

/* 选择框按钮样式 */
.header-search :deep(.el-input-group__append .el-select .el-input__inner) {
  border: none;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 20px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  background-color: transparent;
  color: #fff;
  /* padding-left: 15px; */
  padding-right: 15px;
  width: calc(100% - 10px);
}

/* 选择框下拉箭头样式调整 */
.header-search :deep(.el-select .el-input .el-select__caret) {
  color: #fff;
  right: 8px;
  font-size: 12px;
}

/* 选择框hover状态 */
.header-search :deep(.el-input-group__append:hover) {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 输入框样式微调 */
.header-search :deep(.el-input__inner) {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 下拉菜单样式 */
:deep(.el-select-dropdown__item) {
  padding: 0 10px;
}

:deep(.el-select-dropdown__item.selected) {
  color: #ffbd00;
}

/* 用户头像部分样式优化 */
.avatar-item {
  margin-left: 20px;
  height: 60px;
  line-height: 60px;
}

.avatar-with-text {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-label {
  color: #fff;
  font-size: 14px;
}

/* 调整主内容区域的上边距 */
.el-main {
  margin-top: 60px;
  padding-top: 20px;
}

/* 菜单项样式优化 */
.el-menu-item {
  height: 59px !important;
  line-height: 59px !important;
  padding: 0 20px;
  font-size: 15px;
  border-bottom: none !important;
}

.el-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

/* 下拉菜单样式 */
:deep(.el-submenu__title) {
  height: 60px;
  line-height: 60px;
  padding: 0 15px;
  border-bottom: none !important;
}

:deep(.el-submenu .el-menu-item) {
  height: 40px !important;
  line-height: 40px !important;
  padding: 0 15px;
  margin: 0;
  border-bottom: none !important;
}

:deep(.el-submenu .el-menu) {
  padding: 5px 0;
}

:deep(.el-select .el-input) {
  width: 110px;
}

/* 优化头像样式 */
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.2);
  background-color: #2c3e50; /* 添加背景色 */
  transition: all 0.3s ease;
}
/* 管理员头像样式 */
.admin-avatar {
  background: linear-gradient(45deg, rgba(255, 189, 0, 0.1), rgba(255, 189, 0, 0.2));
  border-radius: 8px;
  padding: 4px 12px;
}

.admin-avatar .avatar {
  position: relative;
  border: 2px solid #FFBD00;
}

.admin-badge {
  position: absolute;
  right: -4px;
  top: -4px;
  background: #FFBD00;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.admin-badge i {
  color: #fff;
  font-size: 12px;
}

/* 管理员菜单项样式 */
.admin-menu-item {
  color: #FFBD00 !important;
  font-weight: 500;
}

.admin-menu-item:hover {
  background-color: rgba(255, 189, 0, 0.1) !important;
}

.admin-avatar:hover {
  background: linear-gradient(45deg, rgba(255, 189, 0, 0.2), rgba(255, 189, 0, 0.3));
}

.mobile-menu-item:active {
  background-color: #f9f9f9;
}

/* 响应式字体大小 */
@media (max-width: 480px) {
  body {
    font-size: 14px;
  }
  
  .el-main {
    padding: 10px;
    margin-top: 50px;
  }
  
  .fixed-header {
    height: 50px;
  }
  
  .el-menu-demo {
    height: 50px;
    padding: 0 10px;
  }
  
  .logo-item {
    height: 50px;
  }
  
  .navbar-header .navbar-brand .community-logo {
    height: 25px;
  }
}

/* 移动端适配 - 为底部导航留出空间 */
@media (max-width: 768px) {
  .el-main {
    padding-bottom: 60px;
  }
  
  .notification-container {
    right: 70px;
  }
  
  .avatar-item {
    right: 10px;
  }
}

/* 添加头像旁边的未读消息红点样式 */
.unread-notification-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 12px;
  height: 12px;
  background-color: #f56c6c;
  border-radius: 50%;
  border: 2px solid #000000; /* 黑色边框，与导航背景色匹配 */
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.2); /* 添加白色发光效果 */
  z-index: 2;
  animation: pulse 2s infinite; /* 添加脉动动画 */
}

/* 添加脉动动画 */
@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7);
  }
  70% {
    transform: scale(1.1);
    box-shadow: 0 0 0 4px rgba(245, 108, 108, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

/* 添加菜单项中的通知数量徽章样式 */
.menu-notification-badge {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 16px;
  margin-left: 8px;
  min-width: 16px;
  text-align: center;
}

/* 移动端菜单通知徽章样式 */
.mobile-menu-notification-badge {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 16px;
  margin-left: 8px;
  min-width: 16px;
  text-align: center;
}

/* 确保移动端头像也有相对定位 */
.mobile-user-info .avatar {
  position: relative;
}

.mobile-menu-item {
  position: relative;
  padding: 15px 20px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}
</style>
